import {
  updateAdminInfoAPI,
  adminLoginAPI,
  adminLogoutAPI,
  adminInfoAPI,
  updateAdminPasswordAPI,
} from '@/api'
import errorLogger from '@/utils/errorLogger'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'

export const useAdminStore = defineStore('admin', {
  state: () => ({
    adminInfo: {},
    token: '',
  }),
  actions: {
    clearToken() {
      this.token = ''
      this.adminInfo = {}
    },

    // 获取管理员信息
    async fetchAdminInfo() {
      try {
        const response = await adminInfoAPI()
        this.adminInfo = response.data
      } catch (error) {
        errorLogger(error)
      }
    },

    // 管理员登录
    async adminLogin(data) {
      try {
        const response = await adminLoginAPI(data)
        this.token = response.data.token
        this.adminInfo = response.data.user
        ElMessage.success('登录成功')
      } catch (error) {
        errorLogger(error)
      }
    },

    // 更新管理员信息
    async updateAdminInfo(data) {
      try {
        const response = await updateAdminInfoAPI(data)
        this.adminInfo = response.data
        ElMessage.success('管理员信息更新成功')
      } catch (error) {
        errorLogger(error)
      }
    },

    // 更新管理员密码
    async updateAdminPassword(data) {
      try {
        const response = await updateAdminPasswordAPI(data)
        this.token = response.data
        ElMessage.success('管理员密码更新成功')
      } catch (error) {
        errorLogger(error)
      }
    },

    // 管理员登出
    async adminLogout() {
      try {
        await adminLogoutAPI()
        this.token = ''
        this.adminInfo = {}
        ElMessage.success('欢迎再次登录')
      } catch (error) {
        errorLogger(error)
      }
    },
  },

  // 开启数据持久化
  persist: true,
})
